<template>
    <div>
        <PageTitle :title="form.id ? '编辑发放' : '新增发放'"></PageTitle>
        <Form ref="form" :model="form" :rules="rules" :label-width="80">
            <FormItem label="名称" prop="name">
                <Input :disabled="form.id && type_val == 2 ? true : false" v-model="form.name" style="width: 260px;" />
            </FormItem>
            <FormItem label="类型" prop="type">
                <RadioGroup v-model="form.type" type="button" button-style="solid">
                    <Radio :disabled="form.id ? true : false" :label="1">新注册用户</Radio>
                    <Radio :disabled="form.id ? true : false" :label="2">指定用户</Radio>
                </RadioGroup>
            </FormItem>
            <FormItem label="优惠券">
                <Button :disabled="form.id && type_val == 2 ? true : false" type="info" @click="handleOpenCouponModal">选择优惠券</Button>
                <div style="margin-top: 10px;">
                    <Table border :columns="columns_coupon" :data="selectedCoupon"></Table>
                </div>
            </FormItem>
            <FormItem label="发放用户" v-if="form.type == 2">
                <div style="display:flex">
                    <Button :disabled="form.id && type_val == 2 ? true : false" type="info" @click="handleOpenModal">选择用户</Button>
                    <Upload
                        ref="upload"
                        accept=".xls,.xlsx"
                        :action="ajax"
                        :headers="headers"
                        :on-success="handleSuccess"
                        :before-upload="handleBeforeUpload"
                        :on-format-error="handleFormatError"
                        :on-remove="handleRemove"
                    >
                        <Button :disabled="form.id && type_val == 2 ? true : false" icon="ios-cloud-upload-outline" style="margin-left:10px;">导入用户</Button>
                    </Upload>
                    <div style="color: #ccc;margin-left:10px;"><a :href="template_url">下载导入模版</a></div>
                </div>
                <div style="margin-top: 10px;">
                    <Table border :columns="columns_user" :data="selectedUser"></Table>
                </div>
            </FormItem>
            <FormItem label="状态" prop="status" v-show="form.type == 1">
                <RadioGroup v-model="form.status">
                    <Radio :disabled="form.id && type_val == 2 ? true : false" :label="1">启用</Radio>
                    <Radio :disabled="form.id && type_val == 2 ? true : false" :label="-1">禁用</Radio>
                </RadioGroup>
            </FormItem>
            <FormItem>
                <Button :disabled="form.id && type_val == 2 ? true : false" type="primary" :loading="submiting" @click="handleSubmit">提交</Button>
                <Button :disabled="submiting" @click="handleCancel" style="margin-left: 10px;">返回</Button>
            </FormItem>
        </Form>
        <Modal
            v-model="showCouponModal"
            title="选择优惠券"
            width="1200px"
            @on-cancel="handleCancelCouponSelect"
        >
            <CouponSelect ref="coupons" :multiple="true" :value="selectedCoupon"></CouponSelect>
            <div slot="footer">
                <Button @click="handleCancelCouponSelect">取消</Button>
                <Button type="primary" @click="handleCouponSelect">提交</Button>
            </div>
        </Modal>
        <Modal
            v-model="showModal"
            title="选择用户"
            width="1200px"
            @on-cancel="handleCancelSelect"
        >
            <UserSelect ref="users" :multiple="true" :value="selectedUser"></UserSelect>
            <div slot="footer">
                <Button @click="handleCancelSelect">取消</Button>
                <Button type="primary" @click="handleSelect">提交</Button>
            </div>
        </Modal>
        <Spin size="large" fix v-if="isLoading"></Spin>
    </div>
</template>

<script>
import CouponSelect from '@/components/selector/coupon-select.vue'
import UserSelect from '@/components/selector/user-select.vue'
import TableRows from '@/components/utils/table-rows.vue';
import { host } from '@/config/index.js';
import Cookies from 'js-cookie';
export default {
    components: {
        CouponSelect,
        UserSelect,
        TableRows
    },
    data() {
        return {
            template_url: host + '/template/phone_import.xlsx',
            ajax: host + '/market/couponSend/import_user',
            headers: {},
            submiting: false,
            isLoading: false,
            showModal: false,
            selectedUser: [],
            showCouponModal: false,
            selectedCoupon: [],
            type_val: null,
            form: {
                id: '',
                name: '',
                type: 1,
                status: 1,
                detail: [],
                user_ids: '',
            },
            rules: {
                name: [
                    {required: true, message: '请输入优惠券名称', trigger: 'blur'}
                ],
                type: [
                    {required: true, type: 'number', message: '请选择类型', trigger: 'change'}
                ],
                status: [
                    {required: true, type: 'number', message: '请选择状态', trigger: 'change'}
                ],
                
            },
            columns_coupon: [
                {
                    title: '名称',
                    minWidth: 100,
                    key: 'name'
                },
                {
                    title: '类型',
                    key: 'type_text'
                },
                {
                    title: '使用范围',
                    key: 'scope_text'
                },
                {
                    title: '使用条件',
                    render: (h, params) => {
                        return h("span", params.row.amount_limit == 0 ? '无限制' : '满' + params.row.amount + '元可用');
                    }
                },
                {
                    title: '面额|折扣',
                    render: (h, params) => {
                        return h("span", params.row.type == 2 ? params.row.scale + '折' : params.row.scale + '元');
                    }
                },
                {
                    title: '有效期',
                    render: (h, params) => {
                        let attr = '';
                        if (params.row.indate_type == 1){
                            attr = [h('p',params.row.indate_stime + '至'), h('p',params.row.indate_etime)];
                        }else{
                            attr = '领取后' + params.row.indate_days + '天有效';
                        }
                        return h('div', attr);
                    }
                },
                {
                    title: '领取限制',
                    render: (h, params) => {
                        return h("span", params.row.get_limit == 0 ? '无限制' : '单用户限领' + params.row.get_number + '张');
                    }
                },
                {
                    title: '发放总量',
                    key: 'total'
                },
                {
                    title: '发放数量',
                    width: 104,
                    render: (h, params) => {
                        return h('div', {
                                style: {
                                    display: 'inline-block'
                                }
                            },[
                                h('InputNumber', {
                                    props: {
                                        disabled: this.form.id && this.type_val == 2 ? true : false,
                                        value: this.form.detail[params.index].number,
                                        min:0,
                                        max: params.row.get_number || 999999
                                    },
                                    style: {
                                        width: '70px'
                                    },
                                    on: {
                                        input: (val) => {
                                            this.form.detail[params.index].number = val;
                                        }
                                    }
                                }),
                            ]
                        )
                    }
                },
                {
                    title: '操作',
                    width: 94,
                    render: (h, params) => {
                        return h('Button', {
                            props: {
                                disabled: this.form.id && this.type_val == 2 ? true : false,
                                size: 'small',
                                type: 'error'
                            },
                            on: {
                                click: () => {
                                    this.selectedCoupon.splice(params.index, 1);
                                    this.form.detail.splice(params.index, 1);
                                }
                            }
                        }, '删除');
                    }
                }
            ],
            columns_user: [
                {
                    title: '用户UID',
                    width:100,
                    key: 'id'
                },
                {
                    title: '用户信息',
                    render: (h, params) => {
                        return h(TableRows, {
                            props: {
                                src: params.row.avatar || '/static/images/default_avatar.png'
                            }
                        }, [
                            h('p',`手机号：${params.row.phone}`)
                        ])
                    }
                },
                {
                    title: '注册时间',
                    key: 'created_at'
                },
                {
                    title: '操作',
                    width: 200,
                    render: (h, params) => {
                        return h('Button', {
                            props: {
                                disabled: (this.form.id && this.type_val == 2) ? true : false,
                                size: 'small',
                                type: 'error'
                            },
                            on: {
                                click: () => {
                                    this.selectedUser.splice(params.index, 1);
                                }
                            }
                        }, '删除');
                    }
                }
            ]
        }
    },
    mounted() {
        if(this.$route.query.id) {
            this.form.id = this.$route.query.id;
            this.handleGetDetail();
        }
        if(Cookies.get('token')) {
            this.headers.Authorization = 'Bearer ' + Cookies.get('token');
        }
    },
    methods: {
        handleGetDetail() {
            this.isLoading = true;
            this.$ajax.get('/market/couponSend/read/'+this.form.id).then(res => {
                this.form = res;
                this.type_val = res.type;
                this.selectedCoupon = res.couponInfo ? res.couponInfo : [];
                this.selectedUser = res.userInfo ? res.userInfo : [];
                this.isLoading = false;
            }).catch(err => {
                this.$Message.error(err.message || '加载失败');
            })
        },
        handleOpenCouponModal() {
            this.$refs.coupons.init();
            this.showCouponModal = true;
        },
        handleCouponSelect() {
            let res = this.$refs.coupons.getCheckeds();
            res.map(item => {
                this.selectedCoupon.push(item);
            })
            this.form.detail = res.map(item => {
                let obj = {
                    coupon_id: item.id,
                    number: 0
                }
                return obj;
            });
            this.handleCancelCouponSelect();
        },
        handleCancelCouponSelect() {
            this.$refs.coupons.clear();
            this.showCouponModal = false;
        },

        handleOpenModal() {
            this.$refs.users.init();
            this.showModal = true;
        },
        handleSelect() {
            let res = this.$refs.users.getCheckeds();
            res.map(item => {
                this.selectedUser.push(item);
            })
            this.handleCancelSelect();
        },
        handleCancelSelect() {
            this.$refs.users.clear();
            this.showModal = false;
        },
        handleSubmit() {
            if(this.submiting) return false;
            this.$refs.form.validate((valid) => {
                if(valid) {
                    const { form } = this;
                    let params = {
                        name: form.name,
                        type: form.type,
                        status: form.status,
                        detail: form.detail
                    };
                    if (params.detail.length == 0){
                        this.$Message.error('优惠券信息不能为空');
                        return false;
                    }
                    if (params.type == 2){
                        params.user_ids = this.selectedUser.map(item => item.id).join(',');
                        if (params.user_ids == ''){
                            this.$Message.error('发放用户不能为空');
                            return false;
                        }
                    }
                    if (form.id) {
                        this.$ajax.put('/market/couponSend/update/'+form.id, params).then(res => {
                            this.$Message.success('编辑成功');
                            this.submiting = false;
                            this.handleCancel();
                        }).catch(err => {
                            this.submiting = false;
                            this.$Message.error(err.message || '提交失败');
                        })
                    }else{
                        this.$ajax.post('/market/couponSend/save', params).then(res => {
                            this.$Message.success('添加成功');
                            this.submiting = false;
                            this.handleCancel();
                        }).catch(err => {
                            this.submiting = false;
                            this.$Message.error(err.message || '提交失败');
                        })
                    }
                }
            })
        },
        handleCancel() {
            this.$router.back();
        },
        //导入
        handleSuccess (res, file, fileList) {
            this.selectedUser = res.data;
        },
        handleFormatError (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: file.name + ' 的格式不正确， 请选择APK格式的文件。'
            });
        },
        handleBeforeUpload () {
            this.$refs.upload.clearFiles();
            return true;
        },
        handleRemove() {
            this.selectedUser = [];
        }
    }
}
</script>